<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\addons\Service;
use think\Exception;

/**
 * 商户
 *
 * @icon fa fa-circle-o
 */
class Store extends Backend
{

    /**
     * Store模型对象
     * @var \app\admin\model\Store
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Store;
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','name','status','create_time']);
                
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 配置
     */
    public function config($ids=null)
    {
        $name = 'epay';
        if (!$name) {
            $this->error(__('Parameter %s can not be empty', 'name'));
        }
        if (!preg_match("/^[a-zA-Z0-9]+$/", $name)) {
            $this->error(__('Addon name incorrect'));
        }
        $info = get_addon_info($name);
        $config = get_addon_fullconfig($name);
        if (!$info) {
            $this->error(__('Addon not exists'));
        }
        $newConfig = $config[$ids] ?? $this->getConfig();
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a", [], 'trim');
            if ($params) {
                foreach ($newConfig  as $k => &$v) {
                    if (isset($params[$v['name']])) {
                        if ($v['type'] == 'array') {
                            $params[$v['name']] = is_array($params[$v['name']]) ? $params[$v['name']] : (array)json_decode($params[$v['name']], true);
                            $value = $params[$v['name']];
                        } else {
                            $value = is_array($params[$v['name']]) ? implode(',', $params[$v['name']]) : $params[$v['name']];
                        }
                        $v['value'] = $value;
                    }
                }
                $config[$ids] = $newConfig;
                try {
                    $addon = get_addon_instance($name);
                    //插件自定义配置实现逻辑
                    if (method_exists($addon, 'config')) {
                        $addon->config($name, $config);
                    } else {
                        //更新配置文件
                        set_addon_fullconfig($name, $config);
                        Service::refresh();
                    }
                } catch (Exception $e) {
                    $this->error(__($e->getMessage()));
                }
                $this->success();
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $tips = [];
        $groupList = [];


        foreach ($newConfig as $index => &$item) {
            //如果有设置分组
            if (isset($item['group']) && $item['group']) {
                if (!in_array($item['group'], $groupList)) {
                    $groupList["custom" . (count($groupList) + 1)] = $item['group'];
                }
            }
            if ($item['name'] == '__tips__') {
                $tips = $item;
                unset($newConfig[$index]);
            }
        }
        $groupList['other'] = '其它';
        $this->view->assign("groupList", $groupList);
        $this->view->assign("ids", $ids);
        $this->view->assign("addon", ['info' => $info, 'config' => $newConfig, 'tips' => $tips]);
        return $this->view->fetch();
    }
    public function getConfig(){
        return [
            [
                'name'    => 'version',
                'title'   => 'API版本(请勿修改该值)',
                'type'    => 'radio',
                'content' => [],
                'value'   => 'v2',
                'rule'    => '',
                'msg'     => '',
                'tip'     => 'V2版本只支持微信支付V2密钥，V3版本只支持微信支付V3密钥，请勿修改该值！！！',
                'ok'      => '',
                'extend'  => '',
            ],
            [
                'name'    => 'wechat',
                'title'   => '微信',
                'type'    => 'array',
                'content' => [],
                'value'   => [
                    'appid'          => '',
                    'app_id'         => '',
                    'app_secret'     => '',
                    'miniapp_id'     => '',
                    'mch_id'         => '',
                    'key'            => '',
                    'key_v3'         => '',
                    'mode'           => 'normal',
                    'sub_mch_id'     => '',
                    'sub_appid'      => '',
                    'sub_app_id'     => '',
                    'sub_miniapp_id' => '',
                    'notify_url'     => '',
                    'cert_client'    => '/addons/epay/certs/apiclient_cert.pem',
                    'cert_key'       => '/addons/epay/certs/apiclient_key.pem',
                    'log'            => '1',
                ],
                'rule'    => 'required',
                'msg'     => '',
                'tip'     => '微信参数配置',
                'ok'      => '',
                'extend'  => '',
            ],
            [
                'name'    => 'alipay',
                'title'   => '支付宝',
                'type'    => 'array',
                'content' => [],
                'value'   => [
                    'app_id'              => '',
                    'mode'                => 'normal',
                    'notify_url'          => '/addons/epay/api/notifyx/type/alipay',
                    'return_url'          => '/addons/epay/api/returnx/type/alipay',
                    'private_key'         => '',
                    'signtype'            => 'cert',
                    'pid'                 => '',
                    'ali_public_key'      => '',
                    'app_cert_public_key' => '',
                    'alipay_root_cert'    => '',
                    'log'                 => '1',
                    'scanpay'             => '0',
                ],
                'rule'    => 'required',
                'msg'     => '',
                'tip'     => '支付宝参数配置',
                'ok'      => '',
                'extend'  => '',
            ]
        ];

    }

}
